package net.starwifi.duobao.interceptor;

import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.oauth.Principal;
import net.starwifi.duobao.service.GglUserService;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.WXUserService;
import net.starwifi.duobao.utils.WebUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;

/**
 * Interceptor - 会员权限
 *
 * @author albertruo@gmail.com
 * @version 1.0
 */
public class MemberwebInterceptor extends HandlerInterceptorAdapter {

	/** 重定向视图名称前缀 */
	private static final String REDIRECT_VIEW_NAME_PREFIX = "redirect:";

	/** "重定向URL"参数名称 */
	private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl";

	/** "会员"属性名称 */
	private static final String MEMBER_ATTRIBUTE_NAME = "member";

	/** 默认登录URL */
	private static final String DEFAULT_LOGIN_URL = "/login";

	/** 登录URL */
	private String loginUrl = DEFAULT_LOGIN_URL;

	@Value("${url_escaping_charset}")
	private String urlEscapingCharset;

	@Resource(name = "memberServiceImpl")
	private MemberService memberService;

	@Resource
	private WXUserService wxUserService;

	@Resource
	private GglUserService gglUserService;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
		if (principal != null) {
			return true;
		}
		String userAgent=request.getHeader("User-Agent");
//		String code=request.getParameter("code"); //如果来源是微信授权返回
//		if(userAgent.contains("MicroMessenger")&&code!=null){
//			UserInfoByCode userInfoByCode=wxUserService.getUserInfo(code);
//			if(userInfoByCode!=null){
//				Member member=memberService.findByWxOpenId(userInfoByCode.getOpenid());
//				if(member!=null){
//					session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(),member.getMobile(),member.getWxOpenId()));
//					return true;
//				}
//				String baseUrl= SettingUtils.get("siteUrl");
//				String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
//				String bindMobileUrl=baseUrl+"/bind/bind-mobile?redirectUrl="+redirectUrl;
//				session.setAttribute("wxAccessToken",userInfoByCode.getAccess_token());
//				session.setAttribute("wxOpenId",userInfoByCode.getOpenid());
//				response.sendRedirect(bindMobileUrl);
//				return false;
//			}
//		}
		String cookieUID= WebUtils.getCookie(request, Member.COOKIE_USERNAME_NAME);
		String cookiePass= WebUtils.getCookie(request,Member.COOKIE_PASS_NAME);
		if(cookiePass==null||cookieUID==null){
			timeOut(request, response, handler);
			return false;
		}
		Member member=memberService.findByUsername(cookieUID);
		if(member==null){
			timeOut(request,response,handler);
			return false;
		}
		String pass= DigestUtils.md5Hex(userAgent + member.getPassword());
		if(!member.getIsEnabled()){
			timeOut(request,response,handler);
			return false;
		}
		if(!pass.equals(cookiePass)){
			timeOut(request,response,handler);
			return false;
		}
		//获取登录时间
		gglUserService.saveLog(member);
		session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(),member.getMobile(),member.getWxOpenId()));
		session.setAttribute("pMobile",member.getMobile());
		try {
			WebUtils.addCookieWithAge(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
			WebUtils.addCookieWithAge(request, response, Member.COOKIE_PASS_NAME, pass);
		}catch (Exception e){
			e.printStackTrace();
		}
		return super.preHandle(request, response, handler);
	}


	public void timeOut(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
		String userAgent=request.getHeader("User-Agent");
		String requestType = request.getHeader("X-Requested-With");
		if(userAgent.contains("Android_Baoxb")){ //App访问
			response.addHeader("loginStatus", "accessDenied");
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
		}
//		else if(userAgent.contains("MicroMessenger")){ //微信访问
//			String code= net.starwifi.duobao.utils.StringUtils.getUUID();
//			String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
//			request.getSession().setAttribute("wx_code",code);
//			String baseUrl= SettingUtils.get("siteUrl");
//			String loginUrl=wxUserService.getUserAuthUrl(baseUrl+redirectUrl,"snsapi_userinfo",code);
//			response.sendRedirect(loginUrl);
//		}
		else{ //其他访问
			if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
				response.addHeader("loginStatus", "accessDenied");
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
			} else {
				if (request.getMethod().equalsIgnoreCase("GET")) {
					String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
					response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset));
				} else {
					response.sendRedirect(request.getContextPath() + loginUrl);
				}
			}
		}
	}


	/*@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
		if (principal != null) {
			return true;
		} else {
			String requestType = request.getHeader("X-Requested-With");
			if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
				response.addHeader("loginStatus", "accessDenied");
				response.sendError(HttpServletResponse.SC_FORBIDDEN);
				return false;
			} else {
				if (request.getMethod().equalsIgnoreCase("GET")) {
					String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
					response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset));
				} else {
					response.sendRedirect(request.getContextPath() + loginUrl);
				}
				return false;
			}
		}
	}*/


	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if (modelAndView != null) {
			String viewName = modelAndView.getViewName();
			if (!StringUtils.startsWith(viewName, REDIRECT_VIEW_NAME_PREFIX)) {
				modelAndView.addObject(MEMBER_ATTRIBUTE_NAME, memberService.getCurrent());
			}
		}
	}

	/**
	 * 获取登录URL
	 * 
	 * @return 登录URL
	 */
	public String getLoginUrl() {
		return loginUrl;
	}

	/**
	 * 设置登录URL
	 * 
	 * @param loginUrl
	 *            登录URL
	 */
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

}